package so.shanku.essential.activity;

import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.adapter.RelationProductAdapter;
import so.shanku.essential.getdata.*;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Jaelyn on 16/4/1.
 * 搜索商品
 */
public class ProductSearchActivity extends BaseActivity {

    /**
     * 搜索框的隐藏与显示
     */
    @ViewInject(id = R.id.linearlayout_search)
    private LinearLayout linearlayout_search;
    /**
     * 搜索商品
     */
    @ViewInject(id = R.id.search_ed)
    private EditText search_ed;
    @ViewInject(id = R.id.do_search_iv, click = "do_search_iv_click")
    private ImageView do_search_iv;

    /**
     * 清楚搜索内容
     */
    @ViewInject(id = R.id.clear_search_iv, click = "clear_search_iv_click")
    private ImageView clear_search_iv;

    /**
     * 搜索取消
     */
    @ViewInject(id = R.id.tv_search_cancel, click = "tv_search_cancel_click")
    private TextView tv_search_cancel;


    @ViewInject(id = R.id.sort_tv, click = "sort_tv_click")
    private TextView sort_tv;
    @ViewInject(id = R.id.discount_cb)
    private CheckBox discount_cb;
    @ViewInject(id = R.id.self_product_cb)
    private CheckBox self_product_cb;

    @ViewInject(id = R.id.ptr_gv)
    private PullToRefreshGridView ptr_gv;


    /**
     * 侧滑抽屉
     */
    @ViewInject(id = R.id.drawer_layout)
    private DrawerLayout drawer_layout;

    @ViewInject(id = R.id.left_drawer)
    private LinearLayout left_drawer;


    /**
     * 搜索关键字
     */
    private String searchKey;
    private String sortId = "0";
    /**
     * 商品
     */
    private ArrayList<JsonMap<String, Object>> dataList = new ArrayList<JsonMap<String, Object>>();
    private RelationProductAdapter relationProductAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_search_layout);

        ptr_gv.setOnRefreshListener(list_loadMoreListener);
        //loadingToast.show();
        //getServiceData(true);
        ptr_gv.setOnItemClickListener(onItemClickListener);
        self_product_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                getServiceData(true);
            }
        });
        discount_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                getServiceData(true);
            }
        });
        relationProductAdapter = new RelationProductAdapter(mContext);
        relationProductAdapter.setShowDiscri(true);
        ptr_gv.setAdapter(relationProductAdapter);

        linearlayout_search.setVisibility(View.VISIBLE);
        search_ed.setOnEditorActionListener(editorActionListener);
    }

    /**
     * 搜索ime的点击
     */
    private TextView.OnEditorActionListener editorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                searchKey = search_ed.getText().toString();
                if (TextUtils.isEmpty(searchKey)) {
                    toast.showToast(R.string.search_key_null);
                    return true;
                } else {
                    loadingToast.show();
                    getServiceData(true);
                    return true;
                }
            }
            return false;
        }
    };

    public void clear_search_iv_click(View view) {
        search_ed.setText("");
    }

    /**
     * 搜索
     *
     * @param view
     */
    public void do_search_iv_click(View view) {
        searchKey = search_ed.getText().toString();
        if (TextUtils.isEmpty(searchKey)) {
            toast.showToast(R.string.search_key_null);
        } else {
            loadingToast.show();
            nPage = 0;
            getServiceData(true);
        }
    }

    /**
     * 取消搜索
     */
    public void tv_search_cancel_click(View view) {
        finish();
    }

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String productId = dataList.get(position).getStringNoNull("productId");
            seeProductDetail(productId);
        }
    };

    /**
     * Gridview
     */
    PullToRefreshBase.OnRefreshListener2 list_loadMoreListener = new PullToRefreshBase.OnRefreshListener2<GridView>() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
            getServiceData(true);
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
            getServiceData(false);
        }
    };
    /**
     * 获取网络数据  搜索产品的接口
     */
    private int nPage = 0;

    /**
     * @param chearAllData
     */
    private void getServiceData(boolean chearAllData) {
        if (chearAllData) {
            nPage = 0;
            ptr_gv.setMode(PullToRefreshBase.Mode.BOTH);
        }
        HashMap<String, Object> params = new HashMap<String, Object>();
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_SearchProductList);
        queue.setWhat(GetDataConfing.what_SearchProductList);
        params.put("sortId", "" + sortId);
        params.put("isDiscount", discount_cb.isChecked() ? 1 : 0);
        params.put("selfOwened", self_product_cb.isChecked() ? 1 : 0);
        params.put("searchKey", searchKey);
        params.put("nPage", nPage + 1);

        queue.setCallBack(callBack);

        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }

    private void setAdapterData(ArrayList<JsonMap<String, Object>> data) {
        if (data.size() == 0) {
            ptr_gv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            ptr_gv.setMode(PullToRefreshBase.Mode.BOTH);
        }
        if (nPage == 0) {
            this.dataList = data;
            relationProductAdapter = new RelationProductAdapter(this);
            relationProductAdapter.setDatas(data);
            relationProductAdapter.setShowDiscri(true);
            ptr_gv.setAdapter(relationProductAdapter);
        } else {
            this.dataList.addAll(data);
            relationProductAdapter.notifyDataSetChanged();
        }
        nPage++;
    }

    /**
     * 获取服务器数据的返回信息
     */
    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.what_SearchProductList) {
                        ArrayList<JsonMap<String, Object>> data = (ArrayList<JsonMap<String, Object>>) JsonParseHelper.getJsonMap_List_JsonMap(
                                entity.getInfo(), JsonKeys.Key_Info);
                        setAdapterData(data);
                    }
                }
            } else {
                ShowGetDataError.showNetError(mContext);

            }
            loadingToast.dismiss();
            ptr_gv.onRefreshComplete();
        }
    };

}